package com.codeoss.module.sale.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.service.impl.BaseService;
import com.codeoss.module.account.model.AccountTax;
import com.codeoss.module.account.service.IAccountTaxService;
import com.codeoss.module.sale.dao.SaleReturnLineMapper;
import com.codeoss.module.sale.model.SaleReturnLine;
import com.codeoss.module.sale.service.ISaleReturnLineService;
import com.codeoss.module.uom.service.IUomUomConversionService;

@Service
public class SaleReturnLineService extends BaseService<SaleReturnLineMapper, SaleReturnLine>
		implements ISaleReturnLineService {
	@Autowired
	private IAccountTaxService accountTaxService;
	@Autowired
	private IUomUomConversionService uomUomConversionService;

	@Override
	public List<SaleReturnLine> getLineListBySaleReturnId(Long saleReturnId) {
		// TODO Auto-generated method stub
		QueryWrapper<SaleReturnLine> query = new QueryWrapper<SaleReturnLine>();
		query.eq("sale_return_id", saleReturnId);
		return list(query);
	}

	@Transactional
	public void insert(SaleReturnLine saleReturnLine) {
		beforeSave(saleReturnLine, true);
		super.insert(saleReturnLine);
	}

	@Transactional
	public void update(SaleReturnLine saleReturnLine) {
		beforeSave(saleReturnLine, false);
		super.update(saleReturnLine);
	}
	@Transactional
	protected void beforeSave(SaleReturnLine saleReturnLine, boolean isNewRecord) {
		Long productId = saleReturnLine.getProductProductId();
		BigDecimal qtyEntered = saleReturnLine.getQtyEntered();
		BigDecimal priceEntered = saleReturnLine.getPriceEntered();
		Long taxId = saleReturnLine.getAccountTaxId();
		Long uomUomId = saleReturnLine.getUomUomId();
		if (productId != null && qtyEntered != null && priceEntered != null && taxId != null && uomUomId != null) {
			BigDecimal qtyOrdered = uomUomConversionService.convert(productId, uomUomId, qtyEntered);
			saleReturnLine.setQtyReturn(qtyOrdered);
			BigDecimal total = qtyOrdered.multiply(priceEntered);
			AccountTax accountTax = accountTaxService.getById(taxId);
			BigDecimal accountRate = (new BigDecimal(100)).add(accountTax.getRate()).divide(new BigDecimal(100));
			total = total.multiply(accountRate);
			saleReturnLine.setAmountSubtotal(total);
		} else {
			saleReturnLine.setAmountSubtotal(null);
		}
	}
}